package Server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;


public class Server extends Thread {

	private ServerView view;
	private ServerSocket server;
	private ArrayList<ClientConnection> clients;
	
	public Server(ServerView view, int port) throws IOException {
		this.view = view;
		this.server = new ServerSocket(port);
		this.clients = new ArrayList<ClientConnection>();
	}
	
	public void run() {
		try {
			while (true) {
				Socket socket = server.accept();
				ClientConnection thread = new ClientConnection(this, socket);
				thread.start();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@SuppressWarnings("deprecation")
	public void stopConnection() throws IOException {
		for (ClientConnection client : clients) {
			client.close();
			client.stop();
		}
		this.server.close();
	}
	
	public ArrayList<ClientConnection> getClients() {
		return this.clients;
	}
	
	public String getClientList(ClientConnection viewer) {
		String clientList = new String();
		for(ClientConnection client : this.getClients()) {
			if(client != viewer)
				clientList += client.toString() + "|";
		}
		return clientList;
	}
	
	public void addClient(ClientConnection client) {
		this.clients.add(client);
	}
	
	public void removeClient(ClientConnection client) {
		this.clients.remove(client);
	}
	
	public void log(String message) {
		this.view.print(message);
	}

	public ServerView getView() {
		return view;
	}
	
}
